let http = require('http')
let fs = require('fs')
let path = require('path')
let url = require('url')


function reader(cb) {
    fs.readFile(path.resolve('mock/data.json'), 'utf8', function(error, data) {
        // console.log(data);
        if (error) {
            cb({})
        } else {
            cb(JSON.parse(data));
        }
    })
}


http.createServer((req, res) => {
    console.log(url.parse(req.url));
    let { pathname, requery } = url.parse(req.url);

    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
    res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.setHeader("X-Powered-By", ' 3.2.1')
    if (req.method == "OPTIONS") return res.end(); /*让options请求快速返回*/

    if (pathname == "/api/seller") {
        reader((data) => {
            let seller = data.seller;
            let result = { errno: 0, data: seller };
            res.setHeader('Content-Type', "application/json;chartset='utf8'");
            res.end(JSON.stringify(result));
        })
    }

    if (pathname == "/api/goods") {
        reader((data) => {
            let goods = data.goods;
            let result = { errno: 0, data: goods };
            res.setHeader('Content-Type', "application/json;chartset='utf8'");
            res.end(JSON.stringify(result));
        })
    }

    if (pathname == "/api/ratings") {
        reader((data) => {
            let ratings = data.ratings;
            let result = { errno: 0, data: ratings };
            res.setHeader('Content-Type', "application/json;chartset='utf8'");
            res.end(JSON.stringify(result));
        })
    }



}).listen(3000);